package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.heima.model.admin.dtos.ChannelDto;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {
    /**
     * 根据查询条件分页查询频道列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findPageListMsg(ChannelDto dto) {
        //1.参数检测
        if (dto == null) {
            //如果查询条件为null  参数错误就返回错误信息:  无效的参数
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //如果没有分页条件设置分页条件
        dto.checkParam();
        //2.按名称模糊分页查询
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(dto.getName())) {
            //如果名字不为空 按名字查询一下
            queryWrapper.like(AdChannel::getName, dto.getName());

        }
        if (dto.getStatus() != null) {
            queryWrapper.eq(AdChannel::getStatus, dto.getStatus());
        }
        //分页
        IPage<AdChannel> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<AdChannel> pageResult = page(pageParam, queryWrapper);
        List<AdChannel> records = pageResult.getRecords();
        Collections.sort(records, new Comparator<AdChannel>() {
            @Override
            public int compare(AdChannel o1, AdChannel o2) {
                int i = o1.getOrd() - o2.getOrd();
                if (i == 0) {
                    return o1.getOrd() - o2.getOrd();
                }
                return i;
            }
        });
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal(), records);
        //3.结果封装
        return responseResult;
    }
    /**
     * 新增
     *
     * @param adChannel
     * @return
     */
    @Override
    @Transactional
    public ResponseResult insert(AdChannel adChannel) {
        //1.参数校验
        if (adChannel == null || StringUtils.isBlank(adChannel.getName())) {
            //非法参数异常
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //如果名字相同的话也不能够新增
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdChannel::getName, adChannel.getName());
        if (getOne(queryWrapper) != null) {
            //数据已经存在不能够新增
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        if (!adChannel.getIsDefault()) {
            save(adChannel);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //查看默认状态:如果是默认状态需要修改现在已经存在的默认值
        LambdaQueryWrapper<AdChannel> query = new LambdaQueryWrapper<>();
        query.eq(AdChannel::getIsDefault, 1);
        if (getOne(query) != null) {
            AdChannel one = getOne(query);
            one.setIsDefault(false);
            updata(one);
        }
        //2.逻辑新增
        save(adChannel);

        //3.结果封装
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 修改
     *
     * @param adChannel
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updata(AdChannel adChannel) {
        //1.参数校验
        if (adChannel == null || StringUtils.isBlank(adChannel.getName())) {
            //非法参数异常
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询当前的数据是否包含
        AdChannel adChannelById = getById(adChannel.getId());
        if (adChannelById == null) {//无效参数异常
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断当前需要更新的频道状态 ;如果不是默认状态的话直接更新
        if (adChannel.getIsDefault()!=null&&!adChannel.getIsDefault()) {
            updateById(adChannel);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //名字相同也不能够上传
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdChannel::getName, adChannel.getName());
        AdChannel one1 = getOne(queryWrapper);
        if (one1 != null) {
            if (!one1.getId().equals(adChannel.getId())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.IS_CONTAIN_SAME_NAME);
            }
        }
        //查看默认状态:如果是默认状态需要修改现在已经存在的默认值
        LambdaQueryWrapper<AdChannel> query = new LambdaQueryWrapper<>();
        query.eq(AdChannel::getIsDefault, 1);
        if (getOne(query) != null) {
            AdChannel one = getOne(query);
            one.setIsDefault(false);
            updateById(one);
        }
        //2.逻辑修改
        updateById(adChannel);
        //3.结果封装
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delete(Integer id) {
        //1.参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        AdChannel one = getById(id);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //默认状态和已启用状态不可以删除
        if (one.getIsDefault()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.IS_DEFAULT_REJECT_DELETE);
        }
        if (one.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.IS_INVOKE_REJECT_DELETE);
        }
        //2.逻辑删除
        removeById(id);
        //3.结果封装
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    public ResponseResult moveUp(Integer id) {
        //1.参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        LambdaQueryWrapper<AdChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdChannel::getOrd, id);
        AdChannel one = getOne(wrapper);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<AdChannel> list = this.list();
        Collections.sort(list, new Comparator<AdChannel>() {
            @Override
            public int compare(AdChannel o1, AdChannel o2) {
                int i = o1.getOrd() - o2.getOrd();
                if (i == 0) {
                    return o1.getOrd() - o2.getOrd();
                }
                return i;
            }
        });
        int i = 0;
        int tmp;
        for (AdChannel adChannel : list) {
            if (!id.equals(adChannel.getOrd())) {
                i++;
            } else {
                if (i == 0) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.FIRST_NUMBER);
                } else {
                    tmp = adChannel.getOrd();
                    adChannel.setOrd(list.get(i - 1).getOrd());
                    list.get(i - 1).setOrd(tmp);
                    break;
                }
            }
        }
        System.out.println(list);
        this.updata(list.get(i));
        System.out.println(list.get(i));
        this.updata(list.get(i - 1));
        System.out.println(list.get(i - 1));
//        System.out.println("数据库结果调换"+list);
        ChannelDto channelDto = new ChannelDto();
        channelDto.checkParam();
        ResponseResult pageListMsg = this.findPageListMsg(channelDto);
        return pageListMsg;
    }
    public ResponseResult moveDown(Integer id) {
        //1.参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        LambdaQueryWrapper<AdChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdChannel::getOrd, id);
        AdChannel one = getOne(wrapper);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询所有的表数据  并进行排序
        List<AdChannel> list = this.list();
        Collections.sort(list, new Comparator<AdChannel>() {
            @Override
            public int compare(AdChannel o1, AdChannel o2) {
                int i = o1.getOrd() - o2.getOrd();
                if (i == 0) {
                    return o1.getOrd() - o2.getOrd();
                }
                return i;
            }
        });
        System.out.println(list);
        int i = 0;
        int tmp;
        for (AdChannel adChannel : list) {
            if (!id.equals(adChannel.getOrd())) {
                i++;
            } else if (i == list.size() - 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LAST_NUMBER);
            } else {
                tmp = list.get(i + 1).getOrd();
                list.get(i + 1).setOrd(list.get(i).getOrd());
                list.get(i).setOrd(tmp);
                break;
            }
        }
        this.updata(list.get(i));
        this.updata(list.get(i + 1));
        ChannelDto channelDto = new ChannelDto();
        channelDto.checkParam();
        ResponseResult pageListMsg = this.findPageListMsg(channelDto);
        return pageListMsg;
    }
}
